package com.example.xjtuse_pc.mobilesafe;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xjtuse_pc.receiver.MyAdmin;
import com.example.xjtuse_pc.utils.StreamTools;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class SplashActivity extends Activity {
    protected static final String TAG = "join";
    protected static final int SHOW_UPDATE_DIALOG = 0;
    protected static final int ENTER_HOME = 1;
    protected static final int URL_ERROR = 2;
    protected static final int NETWORK_ERROR = 3;
    protected static final int JSON_ERROR = 4;
    private TextView tv_splash_version;
    private String  description;
    private String apkurl;
    private TextView tv_update_info;
    private SharedPreferences sp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        tv_splash_version= (TextView) findViewById(R.id.tv_splash_version);
        tv_splash_version.setText("版本号" + getVersionName());
        sp=getSharedPreferences("config",MODE_PRIVATE);
        boolean update = sp.getBoolean("update", false);
        //拷贝数据库
        copyDB();
        if(update){
            CheckUpdata();
        }else {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    enterHome();
                }
            },2000);
        }


        AlphaAnimation aa=new AlphaAnimation(0.2f,1.0f);
        aa.setDuration(1000);
        findViewById(R.id.splash).startAnimation(aa);
        tv_update_info= (TextView) findViewById(R.id.tv_update_info);



    }

    /**
     *path = "data/data/com.example.xjtuse_pc.mobilesafe/files/address.db";
     *  拷贝号码归属地数据库 path 把address.db这个数据库拷贝到data/data/《包名》/files/address.db
     */

    private void copyDB() {
        File file=new File(getFilesDir(),"address.db");
        if(file.exists()&&file.length()>0){
            Log.i("join","数据库存在");
        }else {
            try {
               InputStream is= getAssets().open("address.db");
                FileOutputStream fot=new FileOutputStream(file);
                byte[] but=new  byte[1024];
                int len=0;
                while ((len=is.read(but))!=-1){
                    fot.write(but,0,len);
                }
                is.close();
                fot.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


    /*
        检查升级
     */
    private void CheckUpdata() {
        new Thread() {
            @Override
            public void run() {
                Message mes = Message.obtain();
                long startTime = System.currentTimeMillis();
                try {

//                    URL url=new URL("http://192.168.10.45:8080/updateinfo.html");
//                    //联网
//                    HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//                    conn.setRequestMethod("GET");
//                    conn.setConnectTimeout(100000);
//                    int code=conn.getResponseCode();
//                    Log.i("join","联网成功"+code);
                    HttpClient client = new DefaultHttpClient();
                    HttpUriRequest request = new HttpGet("http://192.168.10.35:8080/updateinfo.html");

                    //HttpUriRequest request = new HttpGet("www.baidu.com");
                    Log.i("join","http://192.168.10.35:8080/updateinfo.html");
                    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
                    HttpResponse resp = client.execute(request);

                    int code= resp.getStatusLine().getStatusCode();
                    if(code==200){
                        //联网成功
                        InputStream in = resp.getEntity().getContent();
                        String result=StreamTools.readFromStream(in);
                        Log.i("join","联网成功"+result);
                        JSONObject obj = new JSONObject(result);
                        String version = (String) obj.get("version");
                        description = (String) obj.get("description");
                        apkurl = (String) obj.get("apkurl");
                        Log.i("join",version);
                        // 校验是否有新版本
                        if (getVersionName().equals(version)) {
                            // 版本一致，没有新版本，进入主页面
                            mes.what = ENTER_HOME;
                        } else {
                            // 有新版本，弹出一升级对话框
                            mes.what = SHOW_UPDATE_DIALOG;

                        }
                    }


                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    mes.what = URL_ERROR;
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    mes.what = NETWORK_ERROR;
                    e.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    mes.what = JSON_ERROR;
                } finally {

                    long endTime = System.currentTimeMillis();
                    // 我们花了多少时间
                    long dTime = endTime - startTime;
                    // 2000
                    if (dTime < 2000) {
                        try {
                            Thread.sleep(2000-dTime);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    handler.sendMessage(mes);}}

        }.start();
    }
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOW_UPDATE_DIALOG:// 显示升级的对话框
                    Log.i(TAG, "显示升级的对话框");
                    ShowUpdateDialog();

                    break;
                case ENTER_HOME:// 进入主页面
                    Log.i(TAG, "进入主页面");
                    enterHome();
                    break;

                case URL_ERROR:// URL错误

                    Toast.makeText(getApplicationContext(), "URL错误", Toast.LENGTH_SHORT).show();
                    enterHome();

                    break;

                case NETWORK_ERROR:// 网络异常

                    Toast.makeText(SplashActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;

                case JSON_ERROR:// JSON解析出错
                    Toast.makeText(SplashActivity.this, "JSON解析出错", Toast.LENGTH_SHORT).show();
                    break;

                default:
                    break;
            }
        }

    };

    /*
   *    新版本更新安装对话框
     */
    private void ShowUpdateDialog() {
        AlertDialog.Builder ad= new AlertDialog.Builder(SplashActivity.this);
        ad.setTitle("升级安装包");
        ad.setCancelable(false);//强制升级
        ad.setMessage(description);
        ad.setPositiveButton("升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //检查sdcard是否存在
                Log.i("join",Environment.getExternalStorageDirectory().getAbsolutePath());
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                   Log.i("join",Environment.getExternalStorageDirectory().getAbsolutePath());
                    FinalHttp fh = new FinalHttp();
                    fh.download(apkurl, Environment.getExternalStorageDirectory().getAbsolutePath()+"/mobilesafe2.0.apk", new AjaxCallBack<File>() {
                        @Override
                        public void onSuccess(File file) {
                            //安装apk
                            installApk(file);
                            super.onSuccess(file);
                        }

                        @Override
                        public void onFailure(Throwable t, int errorNo, String strMsg) {
                            t.printStackTrace();
                            Log.i("join",strMsg+errorNo+"");
                            Toast.makeText(getApplicationContext(), "下载失败", Toast.LENGTH_LONG).show();
                            super.onFailure(t, errorNo, strMsg);
                        }

                        @Override
                        public void onLoading(long count, long current) {
                            int progress = (int) (current * 100 / count);
                            tv_update_info.setText("下载进度：" + progress + "%");
                            super.onLoading(count, current);
                        }
                    });
                }else{
                    Toast.makeText(getApplication(),"没有sdcard,请插入",Toast.LENGTH_SHORT).show();
                }

            }
        });
        ad.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                enterHome();
                dialog.dismiss();
            }
        });
        ad.show();
    }

    private void installApk(File file) {
        Intent intent=new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);

    }

    private void enterHome() {
        Intent intent=new Intent(this,HomeActivity.class);
        startActivity(intent);
        finish();
    }

    /*
     * 获取主机的版本号
      */
    private String getVersionName()  {
        //用来管理手机apk
        PackageManager pm=getPackageManager();
        try {
            PackageInfo info =pm.getPackageInfo(getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }




}
